package cn.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.pojo.Bill;
import cn.pojo.Buy;
import cn.pojo.Goods;
import cn.service.BillService;
import cn.service.BillServiceImpl;
import cn.service.GoodsService;
import cn.service.GoodsServiceImp;
import cn.util.DateUtil;
import cn.util.Page;

/**
 * Servlet implementation class MainController
 */
@WebServlet("*.du")
public class GoodsController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger log = Logger.getLogger(MainController.class);
	private GoodsService goodsService = new GoodsServiceImp();
	private BillService billService = new BillServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 获得servlet的请求路径
		String path = request.getServletPath();
		System.out.println("before=" + path);
		path = path.substring(1, path.indexOf("."));
		System.out.println("after=" + path);
		try {
			Class<?> cl = Class.forName("cn.controller.GoodsController");
			Method mt = cl.getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
			mt.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
			request.getSession().setAttribute("ERROR", "此方法不存在");
			response.sendRedirect("jsp/login.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// 3、供应商管理
	public void goodsList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获得页面提交的用户名
		String goodsName = request.getParameter("goodsName");
		goodsName = goodsName == null ? "" : goodsName;
		// 2、获得页码
		String msg = request.getParameter("pageNum");
		Integer pageNum = 1;
		try {
			pageNum = Integer.parseInt(msg);
		} catch (NumberFormatException e) {
			log.debug(e.getMessage());// 捕捉异常
		}
		// 3、构建page对象封装信息
		Page<Goods> page = new Page<Goods>();
		// 4、根据userName获得总条数
		int sum = goodsService.totalCount(goodsName);
		page.init(sum, pageNum);
		// 5、根据用户名进行模糊分页查询
		List<Goods> list = goodsService.getGoodsLike(goodsName, page.getRowNum(), Page.pageCount);
		page.setList(list);
		// 6、保存数据到Model中
		request.setAttribute("PAGE", page);
		request.setAttribute("GOODSNAME", goodsName);
		// 7、到userList.jsp页面去，展示信息
		request.getRequestDispatcher("/WEB-INF/pages/goods.jsp").forward(request, response);
	}

	public void goodsAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		Buy b = new Buy();
		String id = request.getParameter("id");
		String userId = request.getParameter("userId");
		Goods g = goodsService.getGoodsByid(id);
		Timestamp creationDate = DateUtil.convertUtilDateToTimeStamp(new Date());
		Double productCount = Double.parseDouble(request.getParameter("num"));
		Double totalPrice = Double.parseDouble(request.getParameter("num")) * g.getGoodsPrice();
		Integer isPayment = Integer.parseInt(userId);
		Long createdBy = (long) Integer.parseInt(userId);
		b.setBillCode(g.getGoodsCode());
		b.setProductName(g.getGoodsName());
		b.setProductUnit(g.getGoodsUnit());
		b.setProductDesc(g.getGoodsDESC());
		b.setCreationDate(creationDate);
		b.setIsPayment(isPayment);
		b.setProductCount(productCount);
		b.setTotalPrice(totalPrice);
		b.setCreatedBy(createdBy);
		int i = goodsService.toAddGoods(b);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (i == 0) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	public void buyList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1、获得页面提交的用户名
		String productName = request.getParameter("productName");
		productName = productName == null ? "" : productName;
		// 2、获得页码
		String msg = request.getParameter("productName");
		Integer pageNum = 1;
		try {
			pageNum = Integer.parseInt(msg);
		} catch (NumberFormatException e) {
			log.debug(e.getMessage());// 捕捉异常
		}
		// 3、构建page对象封装信息
		Page<Buy> page = new Page<Buy>();
		// 4、根据userName获得总条数
		int sum = goodsService.totalCountByBuy(productName);
		page.init(sum, pageNum);
		// 5、根据用户名进行模糊分页查询
		List<Buy> list = goodsService.getBuyLike(productName, page.getRowNum(), Page.pageCount);
		page.setList(list);
		// 6、保存数据到Model中
		request.setAttribute("PAGE", page);
		request.setAttribute("PRONAME", productName);
		// 7、到userList.jsp页面去，展示信息
		request.getRequestDispatcher("/WEB-INF/pages/buyList.jsp").forward(request, response);
	}

	public void cleanGoods(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String num = request.getParameter("num");
		String[] id = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		List<Buy> list = goodsService.getBuyByid(id);
		for (int i = 0; i < list.size(); i++) {
			Buy b = list.get(i);
			// b.setProductCount(Double.parseDouble(num));
			Bill bill = new Bill();
			bill.setBillCode(b.getBillCode());
			bill.setCreatedBy(b.getCreatedBy());
			bill.setCreationDate(b.getCreationDate());
			bill.setProductName(b.getProductName());
			bill.setProductDesc(b.getProductDesc());
			bill.setProductUnit(b.getProductUnit());
			bill.setTotalPrice(b.getTotalPrice());
			bill.setProductCount(b.getProductCount());
			bill.setIsPayment(b.getIsPayment());
			billService.addBill(bill);
		}
		Integer[] i = goodsService.deleteBatch(id);
		System.out.println("删除了" + i[0] + "条");
		response.sendRedirect("billList.html");
	}

	public void buyRemove(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		int num = goodsService.buyRemove(id);
		response.sendRedirect("buyList.du");
	}

	// 批量删除
	public void deleteBuy(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String id[] = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		Integer[] num = goodsService.deleteBuy(id);
		HttpSession session = request.getSession();
		session.setAttribute("DELETENUM", num[0]);
		response.sendRedirect("buyList.du");

	}
}
